<?php

namespace app\system\controller;

use think\Session;
use think\db;
use app\system\model\AuthGroupAccess;
use app\system\model\AuthGroup;
use app\admin\common\Base;

use app\system\model\{
    Role,
    Authority as AuthorityModel,
    AuthUser as AuthorUserModel
};

/**
 * This files is part of ssrb_jxc
 * 
 * Author: ttitt <378797263@qq.com>
 * 
 * © ssrb_jxc
 */
class Authority extends Base
{
    public function index()
    {
        $data = $this->request->param();
        $menu = $this->getMenu();

        $role = Db::name('role')->where('pid', '<>', 0)->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
        // halt($role);
        $this->assign('role', $role);
        $this->assign('menu', $menu);
        return $this->fetch();
    }

    public function getUser()
    {
        $data = $this->request->param();
        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            $list = Db::name('auth_user')->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();
            self::each($list, 'static::handleUserData');
            // halt($list);
            return $this->grid_data($list, count($list), $page, $limit);
        }
    }

    public function updateUser()
    {
        $data = $this->request->param();
        if (isset($data['password'])) {
            $data['password'] = md5($data['password']);
        }
        $res = Db::name('auth_user')->where('id', $data['id'])->update($data);
        if ($res) {
            return json(['status' => 1, 'msg' => '更新成功']);
        } else {
            return json(['status' => 0, 'msg' => '更新失败']);
        }
    }

    public static function handleUserData(&$v, $k)
    {
        $v['role_name'] = Db::name('role')->where('id', $v['role_id'])->value('name') ?? '';
    }

    public function getAuth(int $id)
    {
        $list = Db::name('menu')->where('pid', 0)->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->select();

        foreach ($list as $key => $value) {
            $list[$key]['count'] = Db::name('menu')->where('pid', $value['id'])->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->count();
            $son = Db::name('menu')->field('b.*')->alias('a')->join('authority b', 'a.id = b.menu_id')->where('a.pid', $value['id'])->where('b.role_id', $id)->where(['a.is_del' => 0, 'b.is_del' => 0, 'a.enterprise_id' => $this->EnterpriseId, 'b.enterprise_id' => $this->EnterpriseId])->select();
            // halt($son);
            $list[$key]['son'] = $son;
            foreach ($son as $k => $v) {
                $list[$key]['son'][$k]['power_ids'] = explode(',', $v['power_ids']);
            }
        }

        $auth_show = Db::name('role')->where('id', $id)->value('auth_show') ?? '';

        $auth_show = $auth_show ? explode(',', $auth_show) : '';

        if ($list) {
            return json(['status' => 1, 'msg' => '获取数据成功', 'list' => $list, 'auth_show' => $auth_show]);
        } else {
            return json(['status' => 0, 'msg' => '获取数据失败']);
        }
    }

    public function editrole()
    {
        $data = $this->request->param();
        $model = new Role();
        // 过滤post数组中的非数据表字段数据
        $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
        if ($result) {
            return json(['status' => 1, 'msg' => '编辑成功']);
        } else {
            return json(['status' => 0, 'msg' => '编辑失败']);
        }
    }

    public function delrole($id)
    {
        $model = new Role();
        $result = $model->allowField(true)->save(['is_del' => 1], ['id' => $id]);
        if ($result) {
            return json(['status' => 1, 'msg' => '删除成功']);
        } else {
            return json(['status' => 0, 'msg' => '删除失败']);
        }
    }

    public function copyrole()
    {
        //pid, id, newname
        $data = $this->request->param();
        $model = new Role();
        $data['enterprise_id'] = $this->EnterpriseId;
        $id = $data['id'];
        unset($data['id']);
        $data['name'] = $data['newname'];
        unset($data['newname']);
        $result = $model->allowField(true)->save($data);
        if ($result) {
            return json(['status' => 1, 'msg' => '添加成功', 'id' => $model->id]);
        } else {
            return json(['status' => 0, 'msg' => '添加失败']);
        }
    }

    public function save()
    {
        extract($this->request->param());
        $arr = [];
        for ($i = 0; $i < count($ids); $i++) {
            $arr[$pids[$i]][] = $ids[$i];
        }
        $data = [];
        foreach ($arr as $key => $value) {
            $data[] = [
                'role_id' => $role_id,
                'menu_id' => $key,
                'power_ids' => implode(',', $value),
                'enterprise_id' => $this->EnterpriseId
            ];
        }



        $res = Db::name('authority')->where('role_id', $role_id)->update(['is_del' => 1]);
        Db::startTrans();
        $m = new AuthorityModel();
        $res = $m->saveAll($data);
        if (!$res) {
            Db::rollback();
            return json(['status' => 0, 'msg' => '操作失败']);
        }

        if (isset($role_all)) {
            $role_all = implode(',', $role_all);
            $result = Db::name('role')->where('id', $role_id)->update(['auth_show' => $role_all]);
            if (!$result) {
                Db::rollback();
                return json(['status' => 0, 'msg' => '添加失败']);
            }
        } else {
            $result = Db::name('role')->where('id', $role_id)->update(['auth_show' => ""]);
        }



        Db::commit();
        return json(['status' => 1, 'msg' => '操作成功']);
    }

    public function add()
    {
        $data = $this->request->param();
        return $this->fetch();
    }

    public function saveuser()
    {
        $data = $this->request->param();
        $m = new AuthorUserModel();
        $authUser = Db::name('auth_user')->where('username', $data['username'])->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->find();
        if ($authUser) {
            return json(['status' => 0, 'msg' => '添加失败，已经有存在的账号了']);
        }
        $data['enterprise_id'] = $this->EnterpriseId;
        $data['password'] = md5($data['password']);
        $res = $m->save($data);
        if (!$res) {
            return json(['status' => 0, 'msg' => '添加失败']);
        }
        return json(['status' => 1, 'msg' => '添加成功']);
    }

    public function edit($id)
    {
        $info = Db::name('auth_user')->where('id', $id)->find();
        $this->assign('info', $info);
        $this->assign('id', $id);
        return $this->fetch();
    }
}
